<?php
namespace Admin\Controller;
use Think\Controller;
/**
 * 接口文档
 */
class DocController extends BaseController {
    /**
     * 接口文档显示页面
     * @return [type] [description]
     */
   public function index(){
       // dump($this->admin_user['id']);
       header('content-type:text/html;charset=utf-8');
       $proid=I('proid',0);
       $keyword=I('keyword');
       if(empty($proid)){
           $this->error('请选择项目',U('Index/index'));
       }
        $id=I('id',0);
        $pro_name=M('project')->where('proid='.$proid)->getField('pro_name');
        $nav=M('api')->alias('a')->join('api_type as t on t.t_id=a.type_id')
            ->field('a.id,a.title,a.proid,t.t_id,t.t_name')->where('a.proid='.$proid)->order('t.sort asc,a.sort asc')->select();
        $nav1=array();
        $no_count_arr = $this->sel_no_read();
        foreach ($nav as $k=>$v){
            $is_read='1';
            if(!isset($nav1[$v['t_id']]['t_name_count'])){
              $nav1[$v['t_id']]['t_name_count']=0;
            }
            if(in_array($v['id'],$no_count_arr)){
              $is_read='0';
              $nav1[$v['t_id']]['t_name_count']++;
            }
            $nav1[$v['t_id']]['t_name']=$v['t_name'];
            $nav1[$v['t_id']]['child'][]=array('id'=>$v['id'],'title'=>$v['title'],'proid'=>$v['proid'],'is_read'=>$is_read);
        }
       if(empty($id) && !empty($nav)){//默认显示第一个接口
           $id=$nav[0]['id'];
       }
        if(!empty($nav)&& $id){
            $data=M('api')->where('id='.$id)->find();
            $data['params']=M('api_params')->where('p_api_id='.$id)->select();
            //修改新增的记录
            $record=M('record')->where('api_id='.$id)->order("create_time desc")->select();
            foreach($record as $rk =>$rv){
                $record[$rk]['create_time_str'] = get_last_time($rv['create_time']);
            }
            $data['record'] = $record;
        }
        

        $this->set_read($id,$this->admin_user['id']);//设置为已读
        $this->assign('data',$data);
        $this->assign('pro_name',$pro_name);
        $this->assign('proid',$proid);
        $this->assign('nav1',$nav1);
        $this->display('indexNew');
   }
   //查询所有未读
   public function sel_no_read(){
        $w_no['user_id'] = $this->admin_user['id'];
        $w_no['is_read'] = '0';
        $res_no_read = M("api_read_record")->where($w_no)->select();
        if(!$res_no_read) $res_no_read=array();
        $no_count= array();
        foreach($res_no_read as $nk =>$nv){
          $no_count[]= $nv['api_id'];
        }
        return $no_count;
   }
  /**
   * 分类管理
  */
    public function typelist(){
        $proid=I('proid',0);
        if(empty($proid)){
            $this->error('请选择项目',U('Index/index'));
        }
        $pro_name=M('project')->where('proid='.$proid)->getField('pro_name');
        $data=M('api_type')->where('proid='.$proid)->order('sort asc')->select();
        $this->assign('data',$data);
        $this->assign('pro_name',$pro_name);
        $this->assign('proid',$proid);
        $this->display();
    }
    /**
     * 删除分类
    */
    public function delType(){
        $t_id=$this->_param('t_id','请选择要删除的分类');
        //有接口不让删
        $api_count=M('api')->where('type_id='.$t_id)->count();
        if($api_count){
            $this->_internalError('请先删除该分类下的接口');
        }
        $ret=M('api_type')->where('t_id='.$t_id)->delete();
        if($ret){
            $this->_success('操作成功');
        }
        $this->_internalError('操作失败');
    }
    /**
     * 保存分类编辑
    */
    public function saveType(){
        $data=array(
            't_id'=>$this->_param('t_id'),
            't_name'=>$this->_param('t_name','请输入分类名'),
            'sort'=>$this->_param('sort','请输入排序数'),
            'proid'=>$this->_param('proid','项目查询失败'),
            't_desc'=>''
        );
        if(empty($data['t_id'])){
            unset($data['t_id']);
            $ret=M('api_type')->add($data);
        }else{
            $ret=M('api_type')->save($data);
        }
        if($ret){
            $this->_success('操作成功');
        }
        $this->_internalError('你没有作任何修改');
    }
    /**
     * 接口编辑页面
    */
    public function editApi(){
        $proid=I('proid',0);
        $id=I('id',0);
        if(empty($proid)){
            $this->error('请选择项目',U('Index/index'));
        }
        if($id){
            $data=M('api')->where('id='.$id)->find();
            $data['param']=M('api_params')->where('p_api_id='.$id)->select();
        }
        $pro_name=M('project')->where('proid='.$proid)->getField('pro_name');
        $typelist=M('api_type')->where('proid='.$proid)->order('sort asc')->select();

        $this->assign('typelist',$typelist);
        $this->assign('data',$data);
        $this->assign('pro_name',$pro_name);
        $this->assign('proid',$proid);
        $this->display();
    }
    /**
     * 删除参数
    */
    public function delParam(){
        $p_id=$this->_param('p_id','查询失败');
        $ret=M('api_params')->where('p_id='.$p_id)->delete();
        if($ret){
            $this->_success('操作成功');
        }
        $this->_internalError('删除失败，你可能重复操作了');
    }


   /**
   *修改 添加 接口
   */
   public function saveApi(){
       /*var tmp={
                    p_id:$(this).find('.delParam').attr('data-id'),
                    p_name:$(this).find('.p_name').val(),
                    p_type:$(this).find('.p_type').val(),
                    p_desc:$(this).find('.p_desc').val(),
                    p_must:$(this).find('.p_must').children('option:selected').val()
       p_api_id
                };*/
       $data=array(
            'id'=>$this->_param('id'),
            'proid'=>$this->_param('proid','项目获取失败'),
           'type_id'=>$this->_param('type_id','请选择接口分类'),
           'title'=>$this->_param('title','请填写接口名'),
           'desc'=>$this->_param('desc'),
           'url'=>$this->_param('url','请填写接口地址'),
           'exam_url'=>$this->_param('exam_url','请填写调用示例'),
            'request_type'=>$this->_param('request_type','请填写请求方式'),
            'json_str'=>$this->_param('json_str','请填写返回值'),
            'sort'=>I('sort',1)
        );
       $params=$this->_param('params');//参数可以不填
       foreach ($params as $k=>$v){
           if(empty($v['p_name'])||empty($v['p_type'])||empty($v['p_desc'])){
                $this->_internalError('如需要传参，参数名、参数类型、参数描述必填');
           }
       }

       //新增修改说明
       $api_record = $this->_param('api_record','请填写变更说明');
       
       if(empty($data['id'])){
            // 添加接口
           unset($data['id']);
            $api_id=M('api')->add($data);
            if(!$api_id){
                $this->_internalError('接口添加失败');
            }

            //查询该项目的用户-给所有该项目的用户都增加记录
            $this->add_noread_record($data['proid'],$api_id);
            //添加修改新增记录
            $this->add_record($api_id,$api_record);
            //有参数就添加
            foreach ($params as $k => $v) {
                $v['p_api_id']=$api_id;
                if(empty($v['p_id'])){
                    M('api_params')->add($v);
                }else{
                    M('api_params')->save($v);
                }
            }
       }else{
            // 编辑接口
            $ret=M('api')->save($data);
            //查询该项目的用户-给所有该项目的用户都增加记录
            $this->add_noread_record($data['proid'],$data['id']);
            //添加修改新增记录
            $this->add_record($data['id'],$api_record);
            //判断有参数就加的加，改的改
            foreach ($params as $k => $v) {
                $v['p_api_id']=$data['id'];
                if(empty($v['p_id'])){
                    M('api_params')->add($v);
                }else{
                    M('api_params')->save($v);
                }
            }

       }

       $this->_success('操作成功');
   }
   //添加修改新增记录
   public function add_record($api_id,$cont){
      $arr_record['api_id'] = $api_id;
      $arr_record['content'] = $cont;
      $arr_record['create_time'] = time();
      M('record')->add($arr_record);
   }
   //查询该项目的用户-给所有该项目的用户都增加记录
   public function add_noread_record($proid,$api_id){
      $w_user['type']='1';
      $all_user = M('admin')->where($w_user)->select();
      if(!$all_user && !isset($all_user[0]['id'])) $all_user=array();
      $have_uid_arrs=array();
      foreach($all_user as $key =>$val){
        if(!$val['proid']){
          $have_uid_arrs[]=$val['id'];
        }else{
          $pro_arr = explode(',',$val['proid']);
          if(in_array($proid,$pro_arr)){
            $have_uid_arrs[]=$val['id'];
          }
        }
      }
      foreach($have_uid_arrs as $ak=>$av){
        //检查存在
        $w_read['user_id'] = $av;
        $w_read['api_id'] = $api_id;
        $res_read = M('api_read_record')->where($w_read)->find();
        if($res_read){
           $read['is_read'] = '0';
           M('api_read_record')->where($w_read)->save($read);
        }else{
          //添加未读记录
          $read['user_id'] = $av;
          $read['api_id'] = $api_id;
          $read['is_read'] = '0';
          $read['create_time'] = time();
          M('api_read_record')->add($read);
        }
      }
   }
   //设为已读
   public function set_read($api_id,$user_id){
    //检查存在
        $w_read['user_id'] = $user_id;
        $w_read['api_id'] = $api_id;
        $arrs['is_read']  = '1';
        $res_read = M('api_read_record')->where($w_read)->save($arrs);
   }

    /**
     * 在当前项目下搜索结果
    */
    public function searchApi(){
        $proid=$this->_param('proid','项目ID缺失!');
        $keyword=$this->_param('keyword','请输入关键字!');
        $ret=M('api')->alias('a')->join('api_type as t on t.t_id=a.type_id')->where(['a.title'=>['like','%'.$keyword.'%'],['a.proid'=>$proid]])->select();
        if(empty($ret)){
            $this->_internalError('未搜索到相关接口!');
        }
        $this->_success('搜索结果',$ret);
    }


   /**
    *删除接口
   */
   public function delApi(){
        $id=$this->_param('id','id不能为空');
        $ret=M('api')->where('id='.$id)->delete();
        if(!$ret){
            $this->_internalError('操作失败');
        }
        // 删除关联参数
        $ret=M('api_params')->where('p_api_id='.$id)->delete();
        $this->_success('操作成功');
   }

    /**
     * 导出文档
    */
    public function exportWord(){
        $proid=$this->_param('proid','项目ID缺失');
        $pro_name=M('project')->where('proid='.$proid)->getField('pro_name');

        header('content-type:text/html;charset=utf-8');
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Disposition: attachment; filename='.$pro_name.'.doc');

        $nav=M('api')->alias('a')->join('api_type as t on t.t_id=a.type_id')
            ->field('a.id,a.title,a.desc,a.url,a.request_type,a.json_str,t.t_id,t.t_name')->where('a.proid='.$proid)->order('t.sort asc,a.sort asc')->select();
        $data=[];
        $model_params=M('api_params');
        foreach ($nav as $k=>$v){
            $data[$v['t_id']]['t_id']=$v['t_id'];
            $data[$v['t_id']]['t_name']=$v['t_name'];
            $api=[
                'id'=>$v['id'],
                'title'=>$v['title'],
                'desc'=>$v['desc'],
                'url'=>$v['url'],
                'request_type'=>$v['request_type'],
                'json_str'=>$v['json_str'],
                'params'=>$model_params->where('p_api_id='.$v['id'])->field('p_id,p_name,p_type,p_must,p_desc')->select()
            ];
            $data[$v['t_id']]['child'][]=$api;
        }
        $this->assign('data',$data);
        $this->assign('pro_name',$pro_name);
        $this->assign('proid',$proid);
        $content=$this->fetch();
        ob_start();//打开缓冲区
        $html='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">';
        $html.=$content;
        $html.='</html>';
        echo $html;//输出
    }


}